// 简单 API 工具，支持可配置 BaseURL/Token 与回退
(function(){
  const API = {
    baseUrl: localStorage.getItem('apiBaseUrl') || '',
    token: localStorage.getItem('authToken') || ''
  };

  function setApiConfig(baseUrl, token){
    API.baseUrl = baseUrl || '';
    API.token = token || '';
    localStorage.setItem('apiBaseUrl', API.baseUrl);
    localStorage.setItem('authToken', API.token);
  }

  function getConfig(){
    return { baseUrl: API.baseUrl, token: API.token };
  }

  async function fetchJSON(path, fallback){
    const url = (API.baseUrl || '') + path;
    try {
      const res = await fetch(url, {
        headers: {
          'Accept': 'application/json',
          ...(API.token ? { 'Authorization': `Bearer ${API.token}` } : {})
        }
      });
      if(!res.ok) throw new Error(`${res.status} ${res.statusText}`);
      return await res.json();
    } catch(e){
      if (fallback !== undefined) return fallback;
      throw e;
    }
  }

  async function postJSON(path, body){
    const url = (API.baseUrl || '') + path;
    const res = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        ...(API.token ? { 'Authorization': `Bearer ${API.token}` } : {})
      },
      body: JSON.stringify(body || {})
    });
    if(!res.ok) throw new Error(`${res.status} ${res.statusText}`);
    return await res.json();
  }

  window.API = { fetchJSON, postJSON, setApiConfig, getConfig };
})();
